#region

using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Options;
using Vin.Extension.Framework.Upload.Options;
using Vin.Tool.AspNetCore.Extension;
using Vin.Tool.AspNetCore.Service;

#endregion

namespace Vin.Extension.Framework.Upload.Service;

public class LocalFileService : VinBaseService
{
    private readonly IOptionsMonitor<UploadOption> _uploadOption;

    public LocalFileService(IOptionsMonitor<UploadOption> uploadOption)
    {
        _uploadOption = uploadOption;
    }

    // ------------------- 私有方法 -------------------

    public async Task<string> UploadAsync(IFormFile file, string baseDir)
    {
        var fileExtension = file.FileExtensionName();
        var ms = new MemoryStream();
        await file.OpenReadStream().CopyToAsync(ms);
        return await UploadAsync(ms.ToArray(), fileExtension, baseDir);
        // var fileName = $"{Guid.NewGuid()}{fileExtension}";
        // var filePath = Path.Combine(AppContext.BaseDirectory, baseDir, fileName);
        // if (!Directory.Exists(Path.GetDirectoryName(filePath)))
        // {
        //     Directory.CreateDirectory(Path.GetDirectoryName(filePath)!);
        // }
        //
        // await using var stream = new FileStream(filePath, FileMode.Create);
        // await file.CopyToAsync(stream);
        //
        // return Path.Join(_uploadOption.CurrentValue.Host, baseDir, "/", fileName);
    }

    public async Task<string> UploadAsync(byte[] file, string extension, string baseDir)
    {
        var fileName = $"{Guid.NewGuid()}{extension}";
        var filePath = Path.Combine(AppContext.BaseDirectory, baseDir, fileName);
        if (!Directory.Exists(Path.GetDirectoryName(filePath)))
        {
            Directory.CreateDirectory(Path.GetDirectoryName(filePath)!);
        }

        await using var stream = new FileStream(filePath, FileMode.Create);
        await stream.WriteAsync(file, 0, file.Length);

        return Path.Join(_uploadOption.CurrentValue.Host, baseDir, "/", fileName);
    }
}